package com.uetoken.cn.base;

import android.content.Context;
import android.content.ContextWrapper;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.View;

import com.blankj.utilcode.util.ActivityUtils;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.uetoken.cn.R;

/**
 * Created by cgspine on 2018/1/7.
 */

public abstract class BaseFragment extends Fragment {
    public QMUITipDialog qmuiTipDialog;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    public void showLoading() {
        try {
            if (qmuiTipDialog == null) {
                qmuiTipDialog = new QMUITipDialog.Builder(getActivity())
                        .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                        .setTipWord(getString(R.string.str_dialog_loading))
                        .create();
            }
            if (qmuiTipDialog.isShowing()) {
                return;
            }
            Context context = ((ContextWrapper) qmuiTipDialog.getContext()).getBaseContext();
            if (ActivityUtils.isActivityAlive(context)) {
                qmuiTipDialog.show();
            } else {
                qmuiTipDialog = null;
            }
        } catch (Exception e) {
            this.qmuiTipDialog = null;
        }
    }

    public void dissmissDialog() {
        try {
            if (qmuiTipDialog != null) {
                if (qmuiTipDialog.isShowing()) { //check if dialog is showing.

                    //get the Context object that was used to great the dialog
                    Context context = ((ContextWrapper) qmuiTipDialog.getContext()).getBaseContext();

                    //if the Context used here was an activity AND it hasn't been finished or destroyed
                    //then dismiss it
                    if (ActivityUtils.isActivityAlive(context)) {
                        qmuiTipDialog.dismiss();
                    } else {
                        qmuiTipDialog = null;
                    }
                }

            }
        } catch (Exception e) {
            this.qmuiTipDialog = null;
        }
    }

    @Override
    public void onDestroy() {
        dissmissDialog();
        super.onDestroy();
    }
}